//
//  Problem2.swift
//  LeetCode
//
//  Created by zhulongiMac02 on 2018/7/31.
//  Copyright © 2018年 zhulongiMac02. All rights reserved.
//

import UIKit

/*
 给定两个非空链表来表示两个非负整数。位数按照逆序方式存储，它们的每个节点只存储单个数字。将两数相加返回一个新的链表。
 
 你可以假设除了数字 0 之外，这两个数字都不会以零开头。
 
 示例：
 输入：(2 -> 4 -> 3) + (5 -> 6 -> 4)
 输出：7 -> 0 -> 8
 原因：342 + 465 = 807
 */
class Problem2 {

    func solution() {
        let l1 = self.firstListNodes()
        let l2 = self.secondListNodes()
        
        let sum = self.addTwoNode(l1, l2, 0)
        printNode(sum)
    }

    func firstListNodes() -> ListNode {
        let array = [6,4,5,0,4,4,9,4,1]
        
        var node = ListNode(array[0])
        let firstNode = node
        for (index, value) in array.enumerated() {
            if index == 0 {
                continue
            }
            
            node.next = ListNode(value);
            node = node.next!;
        }
        return firstNode
    }

    func secondListNodes() -> ListNode {
        let array = [3,8,8,0,3,0,1,4,8]
        
        var node = ListNode(array[0])
        let firstNode = node
        for (index, value) in array.enumerated() {
            if index == 0 {
                continue
            }
            
            node.next = ListNode(value);
            node = node.next!;
        }
        return firstNode
    }

    // count：是2个数相加，大于10，用来记录 加数
    func addTwoNode(_ l1: ListNode?, _ l2: ListNode?, _ count: Int) -> ListNode? {
        let num1 = (l1 != nil) ? (l1?.val)! : 0
        let num2 = (l2 != nil) ? (l2?.val)! : 0
        
        
        let sum = num1 + num2 + count;
        print("num1: \(num1) + num2: \(num2) + count: \(count) = \(sum)")
        if (l1 == nil) && (l2 == nil) && sum == 0 {
            return nil
        }
        
        if (l1 == nil) && (l2 == nil) && num1 == 0 && num2 == 0 {
            return ListNode(count)
        }
        
        let node = ListNode(sum % 10)
        node.next = addTwoNode(l1?.next, l2?.next, sum / 10)
        return node
    }
    
}
